<template>
  <div class="upload-demo">
    <div class="upload-title">{{ title }}</div>
    <t-upload
      v-model="filesModel"
      :autoUpload="false"
      :multiple="true"
      :max="5"
      :size-limit="{ size: 3000000, unit: 'B' }"
      accept="image/*"
      :beforeUpload="beforeUpload"
      :onRemove="onRemove"
      @validate="onValidate"
    >
    </t-upload>
  </div>
</template>

<script setup>
import { defineProps, defineEmits } from "vue";
import { useVModel } from "@vueuse/core";

const props = defineProps({
  title: {
    type: String,
    default: "单选上传",
  },
  files: {
    type: Array,
    default: [],
  },
  url: {
    type: String,
    default: "",
  },
});

const emits = defineEmits(["update:files"]);
const baseImgUrl = "/api/v1/file?uri=";

const filesModel = useVModel(props, "files", emits);
const onValidate = (context) => {
  if (context.type === "FILE_OVER_SIZE_LIMIT") {
    Message.warning("文件大小超出上限");
  }
};

const beforeUpload = (file) => {
  const isJPG = file.type.includes("image");
  if (!isJPG) {
    uni.showToast({
      title: "只能上传图片",
      icon: "error",
    });
    return false;
  }
  const isLt2M = file.size / 1024 / 1024 < 20;
  if (!isLt2M) {
    uni.showToast({
      title: "上传头像图片大小不能超过 20MB!",
      icon: "error",
    });
    return false;
  }

  if (!props.url) return;

  uni.uploadFile({
    url: props.url,
    fileType: "image",
    file: file.raw,
    header: {
      Authorization: "Bearer " + uni.getStorageSync("access_token"),
    },
    success: (res) => {
      const resData = JSON.parse(res.data);
      const data = resData?.data;
      //   console.log("上传成功", data);
      filesModel.value.push({
        ...data,
        url: baseImgUrl + data.picUrl,
        name: data.originalName,
      });
    },
  });

  return false;
};

const onRemove = (context) => {
  //   console.log("删除文件：", context, filesModel.value);
};
</script>

<style scoped lang="less">
.upload-demo {
  background: var(--bg-color-demo, #fff);
  .upload-title {
    font-size: 16px;
    color: var(--td-text-color-primary, rgba(0, 0, 0, 0.9));
    padding: 12px 16px 0;
  }
}
</style>
